const express = require("express");
const timeStamp = require("time-stamp");
const db = require("../db/index");
const router = express.Router();

router.get("/get", function (req, res) {
  const query = req.query;
  let data = db.logs.get("logs").value() || [];
  let mobiles = db.mobiles.get("mobiles").value() || [];
  let all = {};
  mobiles.forEach((mobile) => {
    all[mobile.mobile] = data.filter((item) => item.mobile == mobile.mobile);
  });
  let errData = [];
  mobiles.forEach(function (mobile) {
    var now = Date.now() - 24 * 3600 * 1000;
    let data = all[mobile.mobile].filter((item) => {
      return item.timeStamp && Number(item.timeStamp) > Number(now);
    });
    errData.push(...data);
  });
  data = errData;
  data.sort((a, b) => {
    return Number(b.timeStamp) - Number(a.timeStamp);
  });
  if (query.mobile) {
    data = data.filter((log) => log.mobile == query.mobile);
  }
  if (query.msg) {
    data = data.filter((log) => log.msg.indexOf(query.msg) > -1);
  }
  data = data.filter((item, index) => index < 100);
  data.forEach((log) => {
    log.timeStampFormat = timeStamp(
      "YYYY-MM-DD HH:mm:ss",
      new Date(Number(log.timeStamp))
    );
  });
  return res.json({
    code: 0,
    data,
  });
});
router.get("/getError", function (req, res) {
  const query = req.query;
  let data = db.logs.get("logs").value() || [];
  let mobiles = db.mobiles.get("mobiles").value() || [];
  let all = {};
  mobiles.forEach((mobile) => {
    all[mobile.mobile] = data.filter((item) => item.mobile == mobile.mobile);
  });
  let errData = [];
  mobiles.forEach(function (mobile) {
    let data = all[mobile.mobile];
    data.sort((a, b) => {
      return Number(b.timeStamp) - Number(a.timeStamp);
    });
    if (data.length > 0) {
      var item = data[0];
      if (item.battery <= 20) {
        errData.push(item);
        return;
      }
      let now = Date.now();
      if (now - Number(item.timeStamp || 0) > 10 * 60 * 1000) {
        errData.push(item);
        return;
      }
    }
  });
  data = errData;
  if (query.mobile) {
    data = data.filter((log) => log.mobile == query.mobile);
  }
  if (query.msg) {
    data = data.filter((log) => log.msg.indexOf(query.msg) > -1);
  }
  data.sort((a, b) => {
    return Number(b.timeStamp) - Number(a.timeStamp);
  });
  data.forEach((log) => {
    log.timeStampFormat = timeStamp(
      "YYYY-MM-DD HH:mm:ss",
      new Date(Number(log.timeStamp))
    );
  });
  return res.json({
    code: 0,
    data,
  });
});
router.post("/add", function (req, res) {
  const body = req.body;
  db.logs.get("logs").push(body).write();
  return res.json({
    code: 0,
    data: [],
  });
});

module.exports = router;
